package cn.wx.user.service.impl;

import cn.wx.basic.exception.BusinessException;
import cn.wx.basic.service.impl.BaseServiceImpl;
import cn.wx.basic.util.Md5Utils;
import cn.wx.basic.util.StrUtils;
import cn.wx.user.domain.Logininfo;
import cn.wx.user.domain.User;
import cn.wx.user.mapper.LogininfoMapper;
import cn.wx.user.mapper.UserMapper;
import cn.wx.user.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;



    @Override
    public void phoneRegister(Map<String, String> map) {


        //1.判断为否为空
       if(
        StringUtils.isEmpty(map.get("phone")) ||
                StringUtils.isEmpty(map.get("verifyCode")) ||
                StringUtils.isEmpty(map.get("password")) ||
                StringUtils.isEmpty(map.get("comfirmPassword"))

       ){
            throw new BusinessException("参数不能为空");
       }

       //2.两次密码是否一致
      if(!map.get("password").equals(map.get("comfirmPassword"))){
          throw new BusinessException("两次密码输入不正确");
      }

        // 3. 手机号校验，是否被注册
        User user = userMapper.findByPhone(map.get("phone"));
        if(user!=null){
            throw new BusinessException("该手机号已被注册");
        }
        // 4. 手机验证码是否过期
        Object o = redisTemplate.opsForValue().get(map.get("phone") +"phoneRegisterCode");
        System.out.println(o);
        if(o==null){
            throw new BusinessException("验证码过期");
        }
        // 5. 校验验证码是否正确
        String s = o.toString().split(":")[0];
        if(!s.equalsIgnoreCase(map.get("verifyCode"))){
            throw new BusinessException("验证码输入错误");
        }

        // 6. 保存数据   logininfo
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(map.get("phone"));
        logininfo.setPhone(map.get("phone"));

        //获取颜值
        String complexRandomString = StrUtils.getComplexRandomString(32);
        logininfo.setSalt(complexRandomString);

        //加盐加密
        String password = Md5Utils.encrypByMd5(complexRandomString + map.get("password"));
        logininfo.setPassword(password);

        //添加
        logininfoMapper.save(logininfo);


      //  user，
        User user1 = new User();
        user1.setUsername(map.get("phone"));
        user1.setPassword(password);
        user1.setLogininfo_id(logininfo.getId());
        user1.setPhone(map.get("phone"));
        user1.setSalt(complexRandomString);

        //添加
        userMapper.save(user1);

    }


}
